import type { Ref } from 'vue'

export default function (jsonData: Ref<any>, callback?: () => any) {
  function clearChoose() {
    jsonData.value.blocks.forEach((item: any) => {
      item.focus = false
    })
  }
  let isMove = false
  // 选中
  function choose(e: MouseEvent, idx: number) {
    e.preventDefault()
    e.stopPropagation()
    if (!isMove) {
      const block: any = jsonData.value.blocks[idx]
      if (!e.shiftKey) {
        clearChoose()
      }
      block.focus = true
    }
    isMove = false
  }
  // 初始化位置
  const initPosition = { x: 0, y: 0 }
  // 移动事件回调
  function move(e: MouseEvent) {
    isMove = true
    const { clientX, clientY } = e
    const x = clientX - initPosition.x
    const y = clientY - initPosition.y
    initPosition.x = clientX
    initPosition.y = clientY
    jsonData.value.blocks = jsonData.value.blocks.map((block: any) => {
      if (block.focus) {
        block.style.left += x
        block.style.top += y
      }
      return block
    })
    callback?.()
  }
  function mouseDown(e: MouseEvent, idx: number) {
    initPosition.x = e.clientX
    initPosition.y = e.clientY
    addEventListener('mousemove', move)
  }
  function mouseup(e: MouseEvent) {
    removeEventListener('mousemove', move)
  }
  return {
    mouseDown,
    mouseup,
    choose,
    clearChoose
  }
}
